<?php
// Simple QR code generation endpoint
// No authentication required
// Usage: GET /api/qrcode.php?text=your_text[&size=200][&format=svg|png]

// CORS & preflight
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

$text = isset($_GET['text']) ? trim((string)$_GET['text']) : '';
$size = isset($_GET['size']) ? (int)$_GET['size'] : (isset($_GET['w']) ? (int)$_GET['w'] : 200);
$size = max(64, min(1024, $size)); // constrain size
$format = isset($_GET['format']) ? strtolower($_GET['format']) : 'svg';
$format = in_array($format, ['svg', 'png'], true) ? $format : 'svg';

if ($text === '') {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'success' => false,
        'message' => '缺少必需参数：text'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// Build external QR generation URL (primary: api.qrserver.com, fallback: quickchart.io)
$encoded = urlencode($text);
$primaryUrl = "https://api.qrserver.com/v1/create-qr-code/?size={$size}x{$size}&data={$encoded}&format={$format}";
$fallbackUrl = "https://quickchart.io/qr?text={$encoded}&size={$size}&format={$format}";

$context = stream_context_create([
    'http' => [
        'method' => 'GET',
        'timeout' => 8,
        'ignore_errors' => true,
        'header' => [
            'User-Agent: NZY-QR-Generator/1.0'
        ]
    ],
    'ssl' => [
        'verify_peer' => true,
        'verify_peer_name' => true,
    ]
]);

function outputImage($data, $format) {
    if ($format === 'svg') {
        header('Content-Type: image/svg+xml');
    } else {
        header('Content-Type: image/png');
    }
    // Disable caching to ensure fresh content
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    echo $data;
    exit;
}

// Try primary service
$data = @file_get_contents($primaryUrl, false, $context);
if ($data !== false && strlen($data) > 0) {
    outputImage($data, $format);
}

// Fallback service
$data2 = @file_get_contents($fallbackUrl, false, $context);
if ($data2 !== false && strlen($data2) > 0) {
    outputImage($data2, $format);
}

// If both failed, return JSON error
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
    'success' => false,
    'message' => '二维码生成失败，请稍后重试'
], JSON_UNESCAPED_UNICODE);
exit;